<?php

namespace App\B2BProject;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Area extends Model
{
    protected $fillable = ['id', 'parent_id', 'name', 'level'];

    public function children()
    {
        return $this->hasMany('App\B2BProject\Area', 'parent_id', 'id');
    }

    public function parent()
    {
        return $this->belongsTo('App\B2BProject\Area', 'parent_id', 'id');
    }

    /**
     * 直接通过 ID 获取地区名
     *
     * @param $id
     *
     * @return mixed
     */
    public static function getName($id)
    {
        try {
            $area = Area::findOrFail($id);
        } catch (ModelNotFoundException $e) {
            return '';
        }

        return $area->name;
    }
}
